﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace PwjCy.Lite.Storage.Imp.SqlServer
{
    public class PreparedStatement : AbstractPreparedStatement
    {
        public PreparedStatement(SqlCommand cmd)
            : base(cmd)
        {
            this.InitializeAdapter();
        }
        public override void SetParameter(string key, object val)
        {
            base._command.Parameters.Add(new SqlParameter(key, val));
        }

        public override void SetParameter(string key, object val, System.Data.DbType type, int len)
        {
            base._command.Parameters.Add(MakeParam(key, type, len, ParameterDirection.Input, val));
        }

        public override void SetParameter(string key, object val, System.Data.DbType type, int len, System.Data.ParameterDirection direction)
        {
            base._command.Parameters.Add(MakeParam(key, type, len, direction, val));
        }

        
        public override System.Xml.XmlReader ExecuteXmlReader()
        {
            throw new NotImplementedException();
        }

        protected override void InitializeAdapter()
        {
            base._adapter = new SqlDataAdapter((SqlCommand)base._command);
        }
        private SqlParameter MakeParam(string ParamName, DbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param;
            if (Size > 0)
                param = new SqlParameter(ParamName, DbType2SqlDbType(DbType), Size);
            else
                param = new SqlParameter(ParamName, DbType2SqlDbType(DbType));
            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
                param.Value = Value;
            return param;
        }
        private SqlDbType DbType2SqlDbType(DbType dbType)
        {
            SqlParameter param = new SqlParameter();
            param.DbType = dbType;
            return param.SqlDbType;
        }
    }
}
